package com.bw.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.DigestUtil;
import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.domain.User;
import com.bw.service.MenuService;
import com.bw.service.UserService;
import com.bw.utils.CheckUtil;
import com.bw.utils.MenuUtil;
import com.bw.utils.R;
import com.bw.utils.RegexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author :Beyond🎸🎸
 * @date : 2025-02-28 19:01:38
 * @description Rock and Roll
 * 代码迭代测试
 **/
@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MenuService menuService;

@RequestMapping("tologin")
    public String tologin(){
    return "login";
}
@RequestMapping("loginSave")
    @ResponseBody
    public R loginSave(String username, String password, HttpSession httpSession){

        if(username == null || username.length()<8){
            return R.ERROR(500,"用户名不能为空,且长度不能小于8位");
        }
        if(password==null ||password.length()<6){
            return R.ERROR(500,"密码长度不小于6位");
        }

        User userOk = userService.selectByName(username);
        if(!CheckUtil.mustNumAndLetter(userOk.getPassword())){
            return R.ERROR(500,"密码必须包含字母和数字！！");
        }
        if(userOk==null){
            return R.ERROR(500,"此用户不存在");
        }
        if(!userOk.getPassword().equals(DigestUtil.md5Hex(password))){
            return R.ERROR(500,"密码输入错误！！");
        }
//    登录成功
        httpSession.setAttribute("userInfo",userOk);
//    登录成功后将用户信息、用户角色、权限信息等存放到缓存中
        redisTemplate.opsForValue().set("user:"+ userOk.getId(),userOk);
//        查看用户的角色
       List<Role> roleList = userService.listRoleByUserId(userOk.getId());
       redisTemplate.opsForValue().set("role:"+ userOk.getId(),roleList);
//       查询用户权限
        List<TbMenu> tbMenuList = menuService.list(userOk.getId());
//        转换成树形结构
        List<TbMenu> menuTreeList = MenuUtil.treeMenus(tbMenuList, null);
//    存储到rides
        redisTemplate.opsForValue().set("menu:"+ userOk.getId(),menuTreeList);

        return R.OK();
}

    @ResponseBody
    @RequestMapping("initPWD")
    public R initPWD(String str){
        String md5pwd = DigestUtil.md5Hex(str);
        System.out.println("加密后的密码:"+md5pwd);
        return R.OK("加密后的密码:"+md5pwd);
    }

}
